package com.yun.util.yun.utils.file;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.zip.GZIPOutputStream;


public class GZIPUtil {

    private final static Logger logger = LoggerFactory.getLogger(GZIPUtil.class);

    public static String compressFile(String path, String inFileName) {
        String outFileName = path + inFileName + ".gz";

        FileInputStream in = null;
        FileOutputStream fops = null;
        GZIPOutputStream out = null;
        byte[] buf = new byte[10240];
        int len = 0;
        try {
            in = new FileInputStream(new File(path + inFileName));
            fops = new FileOutputStream(outFileName);
            out = new GZIPOutputStream(fops);
            while (((in.available() > 10240) && (in.read(buf)) > 0)) {
                out.write(buf);
            }
            len = in.available();
            in.read(buf, 0, len);
            out.write(buf, 0, len);
            logger.info("Completing the GZIP file..." + outFileName);
            out.flush();
        } catch (IOException e) {
            logger.error("压缩文件失败", e);
        } finally {
            try {
                if (out != null) {
                    out.close();
                }
            } catch (IOException e) {
                logger.error("", e);
            }
            try {
                if (fops != null) {
                    fops.close();
                }
            } catch (IOException e) {
                logger.error("", e);
            }
            try {
                if (in != null) {
                    in.close();
                }
            } catch (Exception e) {
                logger.error("", e);
            }
        }
        return inFileName + ".gz";
    }

}
